package com.github.ecbp.store.service.controller.server;

import com.alibaba.fastjson.JSON;
import com.github.ecbp.common.api.CommonResult;
import com.github.ecbp.common.data.controller.BaseController;
import com.github.ecbp.common.utils.excel.utils.ExcelUitls;
import com.github.ecbp.common.utils.excel.utils.FileType;
import com.github.ecbp.common.utils.excel.utils.FileTypeJudge;
import com.github.ecbp.store.service.api.FileApi;
import com.github.ecbp.store.service.vo.ExcelMode;
import com.github.ecbp.store.service.vo.ExcelModelListener;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.Collections;
import java.util.List;

/**
 *功能描述:
 * @auther: Created by Alex·He 2020/4/11 23:14
 * @description: 文件功能Controller
 */
@RestController
public class FileApiController extends BaseController implements FileApi {

    @Override
    public CommonResult upload(@RequestParam("file") MultipartFile srcFile) {
        if (srcFile.isEmpty()) {
            return CommonResult.failed();
        }

        //选择了文件，开始上传操作
        try {
            InputStream inputStream = srcFile.getInputStream();
            String originalFilename = srcFile.getOriginalFilename();
            //            String suffixName = getFileFormat(inputStream, originalFilename).toLowerCase();

            List<ExcelMode> result = ExcelUitls.simpleRead(inputStream, Collections.singletonList(new ExcelModelListener()));
            System.out.println(JSON.toJSONString(result));

            // 上传到服务器
            // downLoadToDisk(srcFile, suffixName);
        } catch (Exception e) {
            logger.error("上传异常", e);
        }

        return CommonResult.succeed(1);
    }

    public static String getFileFormat(InputStream inputStream, String originalFilename) throws Exception {
        String type = FileTypeJudge.getFileType(inputStream);
        //PPT,DOC,XLS
        if (FileType.XLS_DOC.getValue().equals(type)) {
            if (originalFilename.endsWith("xls")) {
                return "xls";
            }
            if (originalFilename.endsWith("doc")) {
                return "doc";
            }
        }
        //XLSX
        if (FileType.XLSX_DOCX.getValue().equals(type)) {
            if (originalFilename.endsWith("xlsx")) {
                return "xlsx";
            }
            if (originalFilename.endsWith("docx")) {
                return "docx";
            }
        }
        throw new RuntimeException("没有符合要求的格式!");
    }
}

